package com.sparrow.common.util;

import java.net.URI;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class MysqlUtil {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/game?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        String user = "root";
        String pw = "131452ni";
        createDataBase(url, user, pw);
    }

    /**
     * 如果没有数据库则创建数据库
     */
    public static void tryCreateDBIfNotExist() {
        String url = PropertiesUtil.getProperty("database.url");
        String user = PropertiesUtil.getProperty("database.user");
        String pw = PropertiesUtil.getProperty("database.password");
        MysqlUtil.createDataBase(url, user, pw);
    }

    /**
     * 创建数据库
     * @param url 数据库连接 URL
     * @param user 数据库用户名
     * @param password 数据库密码
     * @throws RuntimeException 当创建数据库过程中出现异常时抛出
     */
    public static void createDataBase(String url, String user, String password) {
        try {
            String databaseName = getDataBaseName(url);
            // 移除 URL 中的数据库名
            url = trimDataBaseName(url);
            // 建立 MySQL 数据库连接
            try (Connection conn = DriverManager.getConnection(url, user, password);
                 Statement stmt = conn.createStatement()) {
                // 创建 MySQL 数据库
                String sql = "CREATE DATABASE IF NOT EXISTS " + databaseName + " CHARACTER SET UTF8";
                stmt.executeUpdate(sql);
            }
        } catch (Exception e) {
            throw new RuntimeException("创建数据库时出现异常", e);
        }
    }

    /**
     * 从数据库连接 URL 中提取数据库名
     * @param url 数据库连接 URL
     * @return 数据库名
     * @throws RuntimeException 当解析 URL 出现异常时抛出
     */
    public static String getDataBaseName(String url) {
        if (url == null || !url.startsWith("jdbc:")) {
            throw new IllegalArgumentException("非法的数据库连接字符串");
        }
        try {
            String sub = url.substring("jdbc:".length());
            URI uri = new URI(sub);
            String path = uri.getPath();
            if (path == null || path.isEmpty()) {
                throw new RuntimeException("无法从URL中解析数据库名");
            }
            String[] segments = path.split("/");
            return segments[segments.length - 1];
        } catch (Exception e) {
            throw new RuntimeException("解析数据库名时出现异常", e);
        }
    }


    public static String trimDataBaseName(String url) {
        try {
            int slashIndex = url.indexOf('/', "jdbc:mysql://".length());
            if (slashIndex == -1) {
                return url;
            }

            int questionIndex = url.indexOf('?', slashIndex);
            if (questionIndex != -1) {
                return url.substring(0, slashIndex) + url.substring(questionIndex);
            } else {
                return url.substring(0, slashIndex);
            }
        } catch (Exception e) {
            throw new RuntimeException("移除数据库名时出现异常", e);
        }
    }

}